package com.atguigu.gmall.product.component;


import com.atguigu.gmall.product.config.MinioConfig;
import io.minio.MinioClient;
import io.minio.PutObjectOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.InputStream;
import java.util.UUID;


/**
 * minio的所有功能
 */
@Component
public class MinioService {

    @Autowired
    MinioClient minioClient;

    @Autowired
    MinioConfig minioConfig;


    public String upload(InputStream inputStream,String bucketName,String fileName) throws Exception{
        if(StringUtils.isEmpty(bucketName)){
            //给默认位置上传
            bucketName = minioConfig.getDefaultBucket();
        }else{
            if(!minioClient.bucketExists(bucketName)){
                minioClient.makeBucket(bucketName);
            }
        }
        fileName = UUID.randomUUID().toString().replace("-","")+"_"+fileName;
        PutObjectOptions options = new PutObjectOptions(inputStream.available(),-1);
        minioClient.putObject(bucketName,fileName,inputStream,options);

        //返回整个文件路径？？？
        //URL+bucket+filename
        String url = "";
        url = minioConfig.getUrl() + "/"+bucketName + "/"+fileName;
        return url;//文件在minio的存储路径
    }
}
